package com.ming.transaction.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ming.transaction.common.Result;
import com.ming.transaction.entity.Goods;
import com.ming.transaction.exception.ServiceException;
import com.ming.transaction.mapper.GoodsMapper;
import com.ming.transaction.service.IGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

import static com.ming.transaction.common.Constant.Filetype;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 陈仕健
 * @since 2023-05-11
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Value("${files.gupload.path}")
    private String GUpLoadPath;

    @Resource
    private HttpServletResponse response;

    /**
     * 用户头像上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    @Override
    public Result uploadImage(MultipartFile file) throws IOException {
        // 获取文件名称
        String originalFilename = file.getOriginalFilename();
        // 获取文件类型
        String type = FileUtil.extName(originalFilename);
        if (!Filetype(type)) {
            throw new ServiceException(405, "图片格式不正确!");
        }
        // 文件存储到磁盘
        File uploadParentFile = new File(GUpLoadPath);
        // 判断配置的文件目录是否存在，若不存在则创建一个新的文件目录
        if (!uploadParentFile.exists()) {
            uploadParentFile.mkdirs();
        }
        // 定义一个文件唯一的标识位
        String uuid = IdUtil.fastSimpleUUID();
        String uurl = uuid + StrUtil.DOT + type;
        // 实际图片路径
        File uploadFile = new File(GUpLoadPath + uurl);
        // 把获取到的文件存储到磁盘目录
        file.transferTo(uploadFile);
        // 文件路径
        String url = "http://localhost:9090/goods/load/" + uurl;
        return Result.success("上传成功", url);
    }

    /**
     * 用户头像获取
     *
     * @param fileUUID
     */
    @Override
    public void dowmloadImage(String fileUUID) throws IOException {
        // 根据文件的唯一标识码获取文件
        File dowmImage = new File(GUpLoadPath + fileUUID);
        response.setDateHeader("Expires", 0);
        response.addHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        ServletOutputStream os = response.getOutputStream();
        os.write(FileUtil.readBytes(dowmImage));
        os.flush();
        os.close();
    }

    /**
     * 用户商品下架
     *
     * @param id
     * @return
     */
    @Override
    public Result upStugoods(Integer id) {
        Goods good = getById(id);
        if (good == null) {
            return Result.fail("该商品不存在，下架失败!");
        }
        good.setStatus(0);
        if (saveOrUpdate(good)) {
            return Result.success("商品下架成功!");
        }
        return Result.fail("商品下架失败!");

    }

    /**
     * 用户商品分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param gname
     * @param classly
     * @return
     */
    @Override
    public Result pageSearch(Integer pageNum, Integer pageSize, String gname, String classly) {
        IPage<Goods> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if (!"".equals(classly)) {
            queryWrapper.like("classly", classly);
        }
        if (!"".equals(gname)) {
            queryWrapper.like("gname", gname);
        }
        return Result.success("商品查询成功!", page(page, queryWrapper));
    }

    /**
     * 上架商品分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param gname
     * @param classly
     * @param unumber
     * @return
     */
    @Override
    public Result pageSearchs(Integer pageNum, Integer pageSize, String gname, String classly, String unumber) {
        IPage<Goods> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if (!"".equals(classly)) {
            queryWrapper.like("classly", classly);
        }
        if (!"".equals(gname)) {
            queryWrapper.like("gname", gname);
        }
        queryWrapper.eq("unumber", unumber);
        return Result.success("商品查询成功!", page(page, queryWrapper));
    }

    /**
     * 商品更新
     * @param goods
     * @return
     */
    @Override
    public Result goodupdate(Goods goods) {
        if (saveOrUpdate(goods)) {
            return Result.success("修改商品成功!");
        }
        return Result.fail("修改商品失败！");
    }

    /**
     * 删除商品
     * @param id
     * @return
     */
    @Override
    public Result deleteById(Integer id) {
        if (removeById(id)) {
            return Result.success("删除商品成功!");
        }
        return Result.fail("删除商品失败！");
    }

    /**
     * 批量删除商品
     * @param ids
     * @return
     */
    @Override
    public Result deleteByIds(List<Integer> ids) {
        if (removeByIds(ids)) {
            return Result.success("批量删除商品成功！");
        }
        return Result.fail("批量删除商品失败！");
    }

    @Override
    public Result saveGoods(Goods goods) {
        if (save(goods)) {
            return Result.success("添加商品成功!");
        }
        return Result.fail("添加商品失败！");
    }
}
